package com.guigu.servicesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.servicesystem.entity.TbLoginLog;
import com.guigu.servicesystem.entity.TbMenu;
import com.guigu.servicesystem.mapper.TbMenuMapper;
import com.guigu.servicesystem.service.TbMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-07-08
 */
@Service
public class TbMenuServiceImpl extends ServiceImpl<TbMenuMapper, TbMenu> implements TbMenuService {

    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {
        QueryWrapper<TbMenu> wrapper = createExample(searchMap);
        //创建page对象
        Page<TbMenu> pageBrand = new Page<>(page,size);
        baseMapper.selectPage(pageBrand,wrapper);
        return Result.ok().data("tbMenu",pageBrand.getRecords()).data("total",pageBrand.getTotal());
    }

    @Override
    public List<Map> findMenuByParentId() {
        List<TbMenu> all= baseMapper.selectList(null);
        return findMenuByParentId("0",all);
    }

    private List<Map> findMenuByParentId(String parentId, List<TbMenu> menuList) {
        ArrayList<Map> maps = new ArrayList<>();
        for(TbMenu menu: menuList) {
            if(menu.getParentId().equals(parentId)) {
                Map map = new HashMap();
                map.put("path", menu.getId());
                map.put("title", menu.getName());
                map.put("icon", menu.getIcon());
                map.put("linkUrl", menu.getUrl());
                map.put("children", findMenuByParentId(menu.getId(), menuList));
                maps.add(map);
            }
        }
            return maps;
    }


    // 根据查询条件封装模块对象
    private QueryWrapper<TbMenu> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbMenu> wrapper = new QueryWrapper<>();
        if(searchMap!=null) {
            if(searchMap.get("id")!=null)
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("name")!=null && !"".equals(searchMap.get("name")))
                wrapper.like("name",searchMap.get("name"));
        }
        return wrapper;
    }
}
